import _locale
_locale._getdefaultlocale = (lambda *args: ('zh_CN', 'utf8'))

import os
import sys
from os.path import dirname, join, exists, isfile
import configparser
from PyQt5 import uic
from PyQt5.pyrcc_main import main as pyrcc5

base_dir = dirname(__file__)


def get_config(section, key):
    cfg_file_path = join(base_dir, 'config.ini')
    config = configparser.ConfigParser()
    config.read(cfg_file_path, 'utf8')
    return config.get(section, key)


def compile_ui_dir(src, out, recurse=False, **compileUi_args):
    if not exists(src) or not exists(out):
        return

    def _map(uidir, mname):
        return out, ''.join(['ui_', mname])

    uic.compileUiDir(src, recurse, _map, **compileUi_args)
    # for ui_file in os.listdir(out):
    #     if ui_file.startswith('ui_') and ui_file.endswith('.py'):
    #         patch_ui_file(join(out, ui_file))


def compile_res_dir(src, out):
    if not exists(src) or not exists(out):
        return
    argv = sys.argv
    for rc_file in os.listdir(src):
        resrc = join(src, rc_file)
        if isfile(resrc) and rc_file.endswith('.qrc'):
            resrc_out = join(out, rc_file[:-4] + '_rc.py')
            if exists(resrc_out):
                os.remove(resrc_out)
            cmd = 'pyrcc5 %s -o %s' % (resrc, resrc_out)
            sys.argv = cmd.split(' ')
            pyrcc5()
    sys.argv = argv


resource_enabled = get_config('rcfile', 'auto_compile')
ui_enabled = get_config('uifile', 'auto_compile')
import_from = '.'
if get_config('rcfile', 'auto_compile') == '1':
    src = join(base_dir, get_config('rcfile', 'res_dir'))
    compile_res_dir(src, src)
    if exists(join(src, '__init__.py')):
        open(join(src, '__init__.py'), mode='w', encoding='utf-8').close()
    import_from = str(get_config('rcfile', 'import_from'))

if get_config('uifile', 'auto_compile') == '1':
    src = join(base_dir, get_config('uifile', 'ui_dir'))
    sys.path.append(src)
    compile_ui_dir(src, base_dir, from_imports=True, import_from=import_from)
